package com.zy.explore.db.infrastructure.plugins.multidbsupport.sqlchange.where;

import com.zy.explore.db.infrastructure.plugins.multidbsupport.sqlchange.Sqlchange;
import com.zy.explore.db.infrastructure.plugins.multidbsupport.sqlchange.base.SqlOper;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * where 条件中空字符判断（ = '' 或 != '' 或 <> ''）
 *
 * @author xiayd
 */
public class SqlWhereEmptyUtils {
    public static void main(String[] args) {
        String sql = "xx = '' and b.yyy !='' and `zzz`='' and id = 'abc' and ccc<>''";
        List<SqlOper> sqlOperList = find(sql);


        System.out.println(Sqlchange.change(sql, sqlOperList));
    }

    private static final Pattern PATTERN1 = Pattern.compile("((\\!?=)|(<>))\\s*''");
    private static final Pattern PATTERN2 = Pattern.compile("`");

    public static List<SqlOper> find(final String sql) {
        List<SqlOper> sqlOperList = new ArrayList<>();

        Matcher matcher = PATTERN1.matcher(sql);
        while (matcher.find()) {
            String str = matcher.group();
            //不等于
            if (str.charAt(0) == '!' || str.charAt(0) == '<') {
                sqlOperList.add(SqlOper.newReplace(matcher.start(), matcher.end(), " is not null "));
            } else {
                sqlOperList.add(SqlOper.newReplace(matcher.start(), matcher.end(), " is null "));
            }
        }

        matcher = PATTERN2.matcher(sql);
        while (matcher.find()) {
            sqlOperList.add(SqlOper.newDelete(matcher.start(), matcher.end()));
        }

        return sqlOperList;
    }
}
